package com.gxa.shop.commons.jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * com.gxa.util.ConnectionFactory
 * User: huangly
 * Date: 2024/11/27 14:14
 * motto:   逆水行舟不进则退
 * Description:   工厂模式
 * Version: v1.0
 */
public class DruidConnectionFactory {
    private  static    DataSource dataSource;
    static{
        //配置对象
        Properties  properties=new Properties();
        //
        try {
            properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("mysql.properties"));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("====配置文件路径错误==");
        }
        //加载配置文件
        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("====文件内容错误==");
        }
    }

    /**
     * 获取连接对象
     * @return
     */
    public   static Connection   openConnection(){
        try {
            return  dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return  null;
        }
    }

    /**
     *  关闭
     * @param connection
     */
    public  static   void  closeConnection(Connection  connection){
         if(connection!=null){
             try {
                 connection.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }
    }



}
